package com.yj.service;

import com.yj.entity.ChatContent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
public class SSEService {

    private static ConcurrentHashMap<String, SseEmitter> sseEmitters = new ConcurrentHashMap<>();

    @Autowired
    private ChatService qytwChatService;

    public SseEmitter subscribe(String userId) {
        // 设置为用不超时
        SseEmitter emitter = new SseEmitter(0L);
        log.info("New client subscribed: " + userId);

        emitter.onError(cause -> {
            log.error("Error in client: " + userId, cause);
            try {
                emitter.send(SseEmitter.event().name("error").data("Error: " + cause.getMessage()));
                emitter.complete();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });

        emitter.onCompletion(() -> {
            log.info("Client completed: " + userId);
            sseEmitters.remove(userId);
        });

        emitter.onTimeout(() -> {
            log.info("Client timed out: " + userId);
            sseEmitters.remove(userId);
        });

        sseEmitters.put(userId, emitter);
        return emitter;
    }


    public void publish(String userId, String message) {
        SseEmitter emitter = sseEmitters.get(userId);
        log.info("New message published: " + message);
        if (emitter!= null) {
            try {
                ChatContent content = qytwChatService.chat(message);
                emitter.send(SseEmitter.event().name("message").data(content));
            } catch (Exception e) {
                log.error("Error sending message to client: " + userId, e);
            }
        }else {
            log.warn("No client found for user: " + userId);
        }
    }



    public void unsubscribe(String userId) {
        SseEmitter emitter = sseEmitters.remove(userId);
        log.info("Client unsubscribed: " + userId);
        if (emitter!= null) {
            try {
                emitter.complete();
            } catch (Exception e) {
                log.error("Error completing client: " + userId, e);
            }
        }
    }
}
